package bot.controller;

import bot.pojo.BossEntry;
import bot.pojo.BossMessages;
import bot.pojo.FriendList;
import bot.pojo.HttpHelp;
import bot.send.msssgin.BossQQEmailSend;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import java.io.*;
import java.util.*;

/**
 * Boss消息推送接口
 * */
@RestController
@RequestMapping("/Boss")
public class BossPlugin {

    private static String COOKIE = "wd_guid=b67ad2c1-b34e-4e55-9927-cd66d194527e; historyState=state; boss_login_mode=app; _bl_uid=99l4mtkd7ye4Ig27gosy9h9i18Is; lastCity=101090300; __zp_seo_uuid__=d00fd25d-6f1d-4f7e-8ea3-2242aecd071f; __g=-; Hm_lvt_194df3105ad7148dcf2b98a91b5e727a=1712297209; __l=r=https%3A%2F%2Fwww.google.com%2F&l=%2Fwww.zhipin.com%2Fweb%2Fuser%2F%3Fka%3Dheader-login&s=3&g=&friend_source=0; wbg=0; wt2=DKyel0Ffm9g8wDwf3P9jEtq7V6VfJYKuWV9LGjN213FNptpIPfdr112JjXnkzqtbhIKeuwRI2RNes41KMl3RiJA~~; zp_at=b6dIGzzbWyJT8kjuBfZ6xCv5ratrPw5Kjd4B9_HnV_g~; Hm_lpvt_194df3105ad7148dcf2b98a91b5e727a=1714709961; __c=1712798700; __a=47422554.1705065487.1705065487.1712798700.276.2.28.276; geek_zp_token=V1RN4gE-X53VtvVtRuzhkfKCu17TvRxCg~";

    private static String SENDQQEMAIL = "2595931767@qq.com";
    private static String JsonTextSavePath = "D:\\BotFile\\JsonText\\";
    @GetMapping("FindMessage")
    public String FindMessage(Long qq) throws IOException, MessagingException, InterruptedException {
        Map<String , Object> head = new HashMap<>();
        head.put("Cookie",COOKIE);
        //获取联系人列表
        BossEntry bossEntry = JSONObject.parseObject(HttpHelp.sendGet("https://www.zhipin.com/wapi/zprelation/friend/geekFilterByLabel", new HashMap<>(), head), BossEntry.class);
        String UserInfoName = JSONObject.parseObject(HttpHelp.sendGet("https://www.zhipin.com/wapi/zpuser/wap/getUserInfo.json", new HashMap<>(), head) , BossEntry.class).getZpData().getName();

        StringBuffer MsgStr = new StringBuffer();
        List<FriendList> find = Find(qq, bossEntry.getZpData().getFriendList());
        if(find.size() != 0){
            for(FriendList data : find){
                //获取消息
                Map<String , Object> pram = new HashMap<>();
                pram.put("bossId",data.getEncryptFriendId());
                List<BossMessages> messages = JSONObject.parseObject(HttpHelp.sendGet("https://www.zhipin.com/wapi/zpchat/geek/historyMsg", pram, head), BossEntry.class).getZpData().getMessages();
                //取最后一条消息，判断是谁发的
                BossMessages bossMessages = messages.get(messages.size() - 1);
                if(!bossMessages.getFrom().getName().equals(UserInfoName)){
                    MsgStr.append("公司:"+data.getBrandName()+"\n").append("发送消息:"+bossMessages.getPushText()+"\n"+"||");
                }
            }
        }
        //保存/更新数据
        SaveJsonText(bossEntry.getZpData().getFriendList() , qq);
        if(null != MsgStr  && !MsgStr.toString().equals("")){
            BossQQEmailSend.sendEmail(SENDQQEMAIL,MsgStr.toString());
        }
        return MsgStr.toString();
    }

    public void SaveJsonText(List<FriendList> list, Long qq) throws IOException {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(JsonTextSavePath).append(qq).append(".txt");

        String string = stringBuffer.toString();
        File file = new File(string);
        FileWriter fileWriter = new FileWriter(file);
        String jsonString = JSONObject.toJSONString(list);
        fileWriter.write(jsonString);
        fileWriter.flush();
    }

    public List<FriendList> Find(Long qq,List<FriendList> list) throws IOException {
        //判断是否有这个QQ保存的文档，有则读取
        String string = new StringBuffer().append(JsonTextSavePath).append(qq).append(".txt").toString();
        File file = new File(string);
        List<FriendList> readlist = new ArrayList<>();
        if(file.exists()){
            StringBuffer readJson = new StringBuffer();
            String read = new String();
            //判断联系人的updatatime参数是否一致,不一致则表示有新消息
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            while ((read = bufferedReader.readLine()) != null){
                readJson.append(read);
            }
            read = null;
            readlist = JSONObject.parseArray(readJson.toString(),FriendList.class);
        }
        List<FriendList> NewMessageList = new ArrayList<>();//有新消息的数据
        //比较两个集合是否有updatatime参数不一致的
        for (FriendList data : list){
            Optional<FriendList> first = readlist.stream().filter(fdata -> fdata.getFriendId().equals(data.getFriendId())).findFirst();
            //存在则判断updatatime是否一致，如果不存在则说明是新会话
            if(first.isPresent()){
               first = readlist.stream().filter(fdata -> fdata.getFriendId().equals(data.getFriendId())  && !fdata.getUpdateTime().equals(data.getUpdateTime()) ).findFirst();
                if(first.isPresent()) {
                    NewMessageList.add(first.get());
                }
            }else {
                NewMessageList.add(data);
            }
        }
        return NewMessageList;
    }
}
